package org.light.simpleauth;

import org.light.domain.Domain;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.exception.ValidateException;
import org.light.generator.Generator;

public class AuthJsGenerator extends Generator{
	protected Domain userDomain;
	protected boolean containsAuth = false;
	
	public AuthJsGenerator(){
		super();
		super.fileName = "auth.js";
	}
	
	public AuthJsGenerator(String packageToken){
		super();
		this.setPackageToken(packageToken);
		super.fileName = "auth.js";
	}
	
	public AuthJsGenerator(Domain userDomain){
		super();
		this.userDomain = userDomain;
		this.setPackageToken(userDomain.getPackageToken());
		super.fileName = "auth.js";
	}
	
	@Override
	public void setPackageToken(String packageToken) {
		this.packageToken = packageToken;
	}
	
	@Override
	public StatementList generateStatementList() throws ValidateException {		
		if (this.containsAuth){
			StatementList sList = new StatementList();
			sList.add(new Statement(1000L,0,"function logout(){"));
			sList.add(new Statement(2000L,1,"$.ajax({"));
			sList.add(new Statement(3000L,2,"type: \"get\","));
			sList.add(new Statement(4000L,2,"url: \"../"+"login"+this.userDomain.getControllerNamingSuffix()+"/logout"+this.userDomain.getCapFirstDomainName()+"\","));
			sList.add(new Statement(4100L,2,"dataType: 'json',"));
			sList.add(new Statement(4200L,2,"contentType:\"application/json;charset=UTF-8\","));
			sList.add(new Statement(5000L,2,"success: function(data, textStatus) {"));
			sList.add(new Statement(6000L,2,"if (data.success) window.location.href=\"../login/index.html\";"));
			sList.add(new Statement(7000L,2,"},"));
			sList.add(new Statement(8000L,2,"complete : function(XMLHttpRequest, textStatus) {"));
			sList.add(new Statement(9000L,2,"},"));
			sList.add(new Statement(10000L,2,"error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sList.add(new Statement(11000L,2,"alert(\"Error:\"+textStatus);"));
			sList.add(new Statement(12000L,2,"alert(errorThrown.toString());"));
			sList.add(new Statement(13000L,2,"}"));
			sList.add(new Statement(14000L,2,"});"));
			sList.add(new Statement(15000L,0,"}"));
			return sList;
		} else {
			StatementList sList = new StatementList();
			sList.add(new Statement(1000L,0,"function logout(){"));
			sList.add(new Statement(6000L,2,"window.location.href=\"../login/index.html\";"));
			sList.add(new Statement(15000L,0,"}"));
			return sList;
		}
	}

	public Domain getUserDomain() {
		return userDomain;
	}

	public void setUserDomain(Domain userDomain) {
		this.userDomain = userDomain;
	}

	public boolean isContainsAuth() {
		return containsAuth;
	}

	public void setContainsAuth(boolean containsAuth) {
		this.containsAuth = containsAuth;
	}
}
